﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace PMS.Logic.CM
{
    public partial class BottleDeliveryAjax : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            String methodName = Request["method"];
            Type type = this.GetType();
            MethodInfo method = type.GetMethod(methodName);
            if (method == null) throw new Exception("method is null");
            try
            {
                method.Invoke(this, null);
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// 获取气瓶发货信息
        /// </summary>
        public void GetBottleDeliveryList()
        {
            List<SearchCondition> listSearch = new List<SearchCondition>();
            if (Request.Form["searchData"] != null)
            {
                string searchData = Request.Form["searchData"];
                listSearch = ModelTools.GetSearchContions(searchData);
                if (listSearch.Where(s => s.Field == "startOrderDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "startOrderDate").FirstOrDefault().Field = "OrderDate";
                }
                if (listSearch.Where(s => s.Field == "endOrderDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "endOrderDate").FirstOrDefault().Field = "OrderDate";
                }
                if (listSearch.Where(s => s.Field == "startReleaseDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "startReleaseDate").FirstOrDefault().Field = "ReleaseDate";
                }
                if (listSearch.Where(s => s.Field == "endReleaseDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "endReleaseDate").FirstOrDefault().Field = "ReleaseDate";
                }
            }
            Expression<Func<View_CM_BottleDelivery, bool>> exp = SearchExpression.FindByGroup<View_CM_BottleDelivery>(listSearch);
            string OrderId = OperateContext.Sort == null ? "CommissionDate" : OperateContext.Sort;
            int count = 0;
            var list = DALSession.Current.View_CM_BottleDeliveryDAL.GetPagedList(OperateContext.Page, OperateContext.Rows, exp, OrderId, false);
            count = DALSession.Current.View_CM_BottleDeliveryDAL.GetCount(exp);
            Response.Write(JsonHelper.toPageJson(list, count));
        }

        /// <summary>
        /// 根据发货ID获取发货细表（即气瓶）信息
        /// </summary>
        public void GetBottleDeliveryByID()
        {
            if (Request["id"] != null)
            {
                int id = Commons.String2Int32(Request["id"]);
                var list = DALSession.Current.View_CM_BottleDeliveryDAL.GetListBy(u => u.DeliveryID == id);
                Response.Write(JsonHelper.toJson(list));
            }
        }

        /// <summary>
        /// 获取发货记录信息
        /// </summary>
        public void GetDeliveryList()
        {
            List<SearchCondition> listSearch = new List<SearchCondition>();
            if (Request.Form["searchData"] != null)
            {
                string searchData = Request.Form["searchData"];
                listSearch = ModelTools.GetSearchContions(searchData);
                if (listSearch.Where(s => s.Field == "startDeliveryDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "startDeliveryDate").FirstOrDefault().Field = "DeliveryDate";
                }
                if (listSearch.Where(s => s.Field == "endDeliveryDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "endDeliveryDate").FirstOrDefault().Field = "DeliveryDate";
                }
            }
            Expression<Func<View_CM_DeliveryList, bool>> exp = SearchExpression.FindByGroup<View_CM_DeliveryList>(listSearch);
            string OrderId = OperateContext.Sort == null ? "DeliveryDate" : OperateContext.Sort;
            int count = 0;
            var list = DALSession.Current.View_CM_DeliveryListDAL.GetPagedList(OperateContext.Page, OperateContext.Rows, exp, OrderId, false);
            count = DALSession.Current.View_CM_DeliveryListDAL.GetCount(exp);
            Response.Write(JsonHelper.toPageJson(list, count));
        }



        /// <summary>
        /// 根据发货ID获取发货主表信息
        /// </summary>
        public void GetDeliveryByID()
        {
            if (Request["id"] != null)
            {
                int id = Commons.String2Int32(Request["id"]);
                var list = DALSession.Current.View_CM_DeliveryListDAL.GetListBy(u => u.ID == id).FirstOrDefault();
                Response.Write(JsonHelper.toJson(list));
            }
        }

        /// <summary>
        /// 添加发货记录
        /// </summary>
        public void AddDelivery()
        {
            if (Request.Form["deliveryInfo"] == null) return;
            //插入发货记录总表
            List<View_CM_BottleDelivery> deliveryList = JsonConvert.DeserializeObject<List<View_CM_BottleDelivery>>(Request.Form["deliveryInfo"]);
            var delivery = deliveryList.FirstOrDefault();
            //生成流水号 FHyyMMdd0002
            string newId = "FH";
            string time = DateTime.Now.ToString("yyMMdd");
            var con = DALSession.Current.CM_DeliveryDAL.GetListBy(c => c.Code.Substring(2, 6) == time, p => p.Code, false).FirstOrDefault();
            if (con == null)
            {
                newId += time + "0001";
            }
            else
            {
                newId += time + (Commons.String2Int32(con.Code.Substring(8, 4)) + 1).ToString().PadLeft(4, '0');
            }
            var perQuot = DALSession.Current.CM_QuotationDAL.GetListBy(p => p.ID == delivery.QuotationID).FirstOrDefault();
            CM_Delivery perNew = new CM_Delivery()
            {
                Code = newId,
                QuotationID = delivery.QuotationID,
                QuotationCode = delivery.QuotationCode,
                ContractID = delivery.ContractID,
                ContractCode = delivery.ContractCode,
                ProductOrderID = delivery.ProductOrderID,
                ProductOrderCode = delivery.ProductOrderCode,
                CustomerID = delivery.CustomerID,
                ReceiveAddressID = perQuot.CusRecAddID,
                InvoiceAddressID = perQuot.CusInvAddID,
                FillPersonID = OperateContext.SessBasicInfo.UserInfo.Id,
                DeliveryDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
            };
            try
            {
                //发货总表ID
                int deliveryID = Commons.String2Int32(DALSession.Current.CM_DeliveryDAL.AddModelReturnId(perNew, "ID"));
                DALSession.Current.CM_DeliveryDAL.SaveChanges();
                //更新气瓶绑定的发货单ID
                deliveryList.ForEach(d =>
                {
                    var bottlePer = DALSession.Current.PM_BottleProductionDAL.GetListBy(p => p.ID == d.ID).FirstOrDefault();
                    bottlePer.DeliveryID = deliveryID;
                    bottlePer.DeliveryCode = newId;
                    //状态更新为发货
                    bottlePer.State = "4";
                    bottlePer.DeliveryDate = perNew.DeliveryDate;
                    DALSession.Current.PM_BottleProductionDAL.ModifyBy(bottlePer, p => p.ID == d.ID, "DeliveryID", "DeliveryCode", "DeliveryDate", "State");
                });
                DALSession.Current.PM_BottleProductionDAL.SaveChanges();
                Response.Write(JsonHelper.toJson(new { deliveryID = deliveryID, state = "success" }));
            }
            catch
            {
                Response.Write(JsonHelper.toDefaultMsg(false, "请重新点击发货按钮！"));
                return;
            }
        }

        /// <summary>
        /// 更新发货记录
        /// </summary>
        public void EditDelivery()
        {
            if (Request["id"] != null)
            {
                int id = Commons.String2Int32(Request["id"]);
                //更新主表
                CM_Delivery perNew = DALSession.Current.CM_DeliveryDAL.GetListBy(u => u.ID == id).FirstOrDefault();
                ModelTools.Form2EditModel(Request.Form, perNew);
                DALSession.Current.CM_DeliveryDAL.ModifyAllModel(perNew);
                DALSession.Current.CM_DeliveryDAL.SaveChanges();
                Response.Write(JsonHelper.toDefaultMsg(true, "保存成功"));
            }
        }

        /// <summary>
        /// 删除发货记录
        /// </summary>
        public void DelDelivery()
        {
            if (Request["id"] != null)
            {
                int id = Commons.String2Int32(Request["id"]);
                //删除主表
                DALSession.Current.CM_DeliveryDAL.DelBy(p => p.ID == id);
                DALSession.Current.CM_DeliveryDAL.SaveChanges();
                //更新气瓶绑定的发货单号与状态
                var list = DALSession.Current.PM_BottleProductionDAL.GetListBy(p => p.DeliveryID == id);
                list.ForEach(d =>
                {
                    d.DeliveryCode = null;
                    d.DeliveryID = null;
                    d.DeliveryDate = null;
                    //将状态改为入库完成
                    d.State = "3";
                    DALSession.Current.PM_BottleProductionDAL.ModifyBy(d, b => b.ID == d.ID, "State", "DeliveryID", "DeliveryCode", "DeliveryDate");
                });
                DALSession.Current.PM_BottleProductionDAL.SaveChanges();
                Response.Write(JsonHelper.toDefaultMsg(true, "删除成功"));
            }
        }

        /// <summary>
        /// 根据生产订单号获取可以追加的气瓶
        /// </summary>
        public void GetAddibleBottle()
        {
            if (Request["pdCode"] != null)
            {
                string pdCode = Request["pdCode"];
                //生产订单号相等，且没有绑定发货单ID,且气瓶状态为入库完成
                var bottleList = DALSession.Current.View_CM_BottleDeliveryDAL.GetListBy(b => b.ProductOrderCode == pdCode && b.DeliveryID == null && b.State == "3");
                Response.Write(JsonHelper.toJson(bottleList));
            }
        }

        /// <summary>
        /// 为发货单追加气瓶
        /// </summary>
        public void AddBottle2Delivery()
        {
            if (Request["id"] != null)
            {
                if (Request.Form["BottleInfo"] == null) return;
                //发货单ID
                int deliveryID = Commons.String2Int32(Request["id"]);
                var delivery = DALSession.Current.CM_DeliveryDAL.GetListBy(p => p.ID == deliveryID).FirstOrDefault();
                var bottleList = JsonConvert.DeserializeObject<List<View_CM_BottleDelivery>>(Request.Form["BottleInfo"]);
                //将要追加的气瓶与发货单进行绑定
                bottleList.ForEach(d =>
                {
                    var bottlePer = DALSession.Current.PM_BottleProductionDAL.GetListBy(p => p.ID == d.ID).FirstOrDefault();
                    bottlePer.DeliveryID = deliveryID;
                    bottlePer.DeliveryCode = delivery.Code;
                    bottlePer.DeliveryDate = delivery.DeliveryDate;
                    //状态更新为发货
                    bottlePer.State = "4";
                    DALSession.Current.PM_BottleProductionDAL.ModifyBy(bottlePer, p => p.ID == d.ID, "DeliveryID", "DeliveryDate", "DeliveryCode", "State");
                });
                DALSession.Current.PM_BottleProductionDAL.SaveChanges();
                Response.Write(JsonHelper.toDefaultMsg(true, "追加成功"));
            }
        }

        /// <summary>
        /// 从发货单中删除气瓶
        /// </summary>
        public void DelBottleFromDelivery()
        {
            if (Request.Form["BottleInfo"] == null) return;
            var bottleList = JsonConvert.DeserializeObject<List<View_CM_BottleDelivery>>(Request.Form["BottleInfo"]);
            //将要删除的气瓶与发货单取消绑定
            bottleList.ForEach(d =>
            {
                var bottlePer = DALSession.Current.PM_BottleProductionDAL.GetListBy(p => p.ID == d.ID).FirstOrDefault();
                bottlePer.DeliveryID = null;
                bottlePer.DeliveryCode = null;
                bottlePer.DeliveryDate = null;
                //将状态改为入库完成
                bottlePer.State = "3";
                DALSession.Current.PM_BottleProductionDAL.ModifyAllModel(bottlePer);
            });
            DALSession.Current.PM_BottleProductionDAL.SaveChanges();
            Response.Write(JsonHelper.toDefaultMsg(true, "删除成功"));
        }



        /// <summary>
        /// 扫码入库
        /// </summary>
        public void ScanInStorage()
        {
            if (Request.Form["BarCode"] == null) return;
            string barcode = Request.Form["BarCode"];
            var per = DALSession.Current.PM_BottleProductionDAL.GetListBy(p => p.SerialCode == barcode).FirstOrDefault();
            if (per.State != "2")
            {
                Response.Write(JsonHelper.toDefaultMsg(false, "当前气瓶状态不是 [分析完成] ,入库失败"));
            }
            else
            {
                per.State = "3";
                per.InStorageDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                per.InStoragePersonID = OperateContext.SessBasicInfo.UserInfo.Id;
                DALSession.Current.PM_BottleProductionDAL.ModifyBy(per, p => p.ID == per.ID, "State", "InStorageDate", "InStoragePersonID");
                DALSession.Current.PM_BottleProductionDAL.SaveChanges();
                Response.Write(JsonHelper.toDefaultMsg(true, "入库成功"));
            }
        }

        /// <summary>
        /// 扫码插入中间表
        /// </summary>
        public void AddDeliveryMiddleRecord()
        {
            if (Request.Form["BarCode"] == null) return;
            string barcode = Request.Form["BarCode"];

            var per = DALSession.Current.PM_BottleProductionDAL.GetListBy(p => p.SerialCode == barcode).FirstOrDefault();
            if (per == null)
            {
                Response.Write(JsonHelper.toDefaultMsg(false, "系统中不存在该气瓶！"));
                return;
            }
            if (per.State != "3")
            {
                Response.Write(JsonHelper.toDefaultMsg(false, "该气瓶状态不是[已入库]，发货失败！"));
                return;
            }
            var isExsit = DALSession.Current.CM_DeliveryMiddleTableDAL.GetListBy(p => p.PersonID == OperateContext.SessBasicInfo.UserInfo.Id && p.BottleProductionID == per.ID).FirstOrDefault();
            if (isExsit != null)
            {
                Response.Write(JsonHelper.toDefaultMsg(false, "不能添加重复气瓶！"));
                return;
            }
            CM_DeliveryMiddleTable perDelivery = new CM_DeliveryMiddleTable()
            {
                PersonID = OperateContext.SessBasicInfo.UserInfo.Id,
                BottleProductionID = per.ID
            };
            DALSession.Current.CM_DeliveryMiddleTableDAL.Add(perDelivery);
            DALSession.Current.CM_DeliveryMiddleTableDAL.SaveChanges();
            Response.Write(JsonHelper.toDefaultMsg(true, "保存成功"));
        }

        /// <summary>
        /// 扫码发货时获取气瓶
        /// </summary>
        public void GetScanDeliveryRecord()
        {
            var list = DALSession.Current.View_CM_ScanDeliveryDAL.GetListBy(p => p.PersonID == OperateContext.SessBasicInfo.UserInfo.Id).ToList();
            Response.Write(JsonHelper.toJson(list));
        }

        /// <summary>
        /// 扫码发货时删除气瓶
        /// </summary>
        public void DelMiddleDeliveryRecord()
        {
            int id = Convert.ToInt32(Request.Form["data"]);
            DALSession.Current.CM_DeliveryMiddleTableDAL.DelBy(p => p.ID == id);
            DALSession.Current.CM_DeliveryMiddleTableDAL.SaveChanges();
            Response.Write(JsonHelper.toDefaultMsg(true, "删除成功！"));
        }

        /// <summary>
        /// 扫码页面添加发货记录
        /// </summary>
        public void AddDeliveryByScan()
        {
            if (Request.Form["deliveryInfo"] == null) return;
            //插入发货记录总表
            List<View_CM_ScanDelivery> deliveryList = JsonConvert.DeserializeObject<List<View_CM_ScanDelivery>>(Request.Form["deliveryInfo"]);
            var delivery = deliveryList.FirstOrDefault();
            //生成流水号 FHyyMMdd0002
            string newId = "FH";
            string time = DateTime.Now.ToString("yyMMdd");
            var con = DALSession.Current.CM_DeliveryDAL.GetListBy(c => c.Code.Substring(2, 6) == time, p => p.Code, false).FirstOrDefault();
            if (con == null)
            {
                newId += time + "0001";
            }
            else
            {
                newId += time + (Commons.String2Int32(con.Code.Substring(8, 4)) + 1).ToString().PadLeft(4, '0');
            }
            var perQuot = DALSession.Current.CM_QuotationDAL.GetListBy(p => p.ID == delivery.QuotationID).FirstOrDefault();
            CM_Delivery perNew = new CM_Delivery()
            {
                Code = newId,
                QuotationID = delivery.QuotationID,
                QuotationCode = delivery.QuotationCode,
                ContractID = delivery.ContractID,
                ContractCode = delivery.ContractCode,
                ProductOrderID = delivery.ProductOrderID,
                ProductOrderCode = delivery.ProductOrderCode,
                CustomerID = delivery.CustomerID,
                ReceiveAddressID = perQuot.CusRecAddID,
                InvoiceAddressID = perQuot.CusInvAddID,
                FillPersonID = OperateContext.SessBasicInfo.UserInfo.Id,
                DeliveryDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
            };
            try
            {
                //发货总表ID
                int deliveryID = Commons.String2Int32(DALSession.Current.CM_DeliveryDAL.AddModelReturnId(perNew, "ID"));
                DALSession.Current.CM_DeliveryDAL.SaveChanges();
                //更新气瓶绑定的发货单ID
                deliveryList.ForEach(d =>
                {
                    var bottlePer = DALSession.Current.PM_BottleProductionDAL.GetListBy(p => p.ID == d.BottleProductionID).FirstOrDefault();
                    bottlePer.DeliveryID = deliveryID;
                    bottlePer.DeliveryCode = newId;
                    //状态更新为发货
                    bottlePer.State = "4";
                    bottlePer.DeliveryDate = perNew.DeliveryDate;
                    DALSession.Current.PM_BottleProductionDAL.ModifyBy(bottlePer, p => p.ID == d.BottleProductionID, "DeliveryID", "DeliveryCode", "DeliveryDate", "State");
                });
                //删除中间表
                deliveryList.ForEach(d =>
                {
                    DALSession.Current.CM_DeliveryMiddleTableDAL.DelBy(p => p.ID == d.ID);
                });
                DALSession.Current.PM_BottleProductionDAL.SaveChanges();
                DALSession.Current.CM_DeliveryMiddleTableDAL.SaveChanges();

                Response.Write(JsonHelper.toJson(new { deliveryID = deliveryID, state = "success" }));
            }
            catch
            {
                Response.Write(JsonHelper.toDefaultMsg(false, "请重新点击发货按钮！"));
                return;
            }
        }

        /// <summary>
        /// 根据发货单ID获取发货信息，用于打印
        /// </summary>
        public void GetDeliveryForPrint()
        {
            if (Request.Form["ID"] != null && Request.Form["ID"] != "")
            {
                int deliID = Convert.ToInt32(Request.Form["ID"]);
                var per = DALSession.Current.View_CM_DeliveryListDAL.GetListBy(c => c.ID == deliID).FirstOrDefault();
                var companyPer = DALSession.Current.BD_CompanyInfoDAL.GetListBy(c => c.ID == per.CustomerID).FirstOrDefault();

                Response.Write(JsonHelper.toJson(new
                {
                    DeliveryData = per,
                    CompanyData = companyPer
                }));
            }
        }

        /// <summary>
        /// 根据发货单ID获取产品信息，用于打印
        /// </summary>
        public void GetProdDetailForDeliveryPrint()
        {
            if (Request.Form["ID"] != null && Request.Form["ID"] != "")
            {
                int deliID = Convert.ToInt32(Request.Form["ID"]);

                var bottleList = DALSession.Current.PM_BottleProductionDAL.GetListBy(c => c.DeliveryID == deliID);
                List<CM_QuotationDetail> quotList = new List<CM_QuotationDetail>();
                bottleList.ForEach(d =>
                {
                    var quotDetailPer = DALSession.Current.CM_QuotationDetailDAL.GetListBy(c => c.ID == d.QuotationDetailID).FirstOrDefault();
                    //这里用订货数量这一属性来代表相同产品的发货气瓶数量 默认为1瓶
                    quotDetailPer.OrderCount = 1;
                    //若两瓶气的产品ID一致，则可累加
                    var sameQuot = quotList.Where(c => c.ID == quotDetailPer.ID).FirstOrDefault();
                    if (sameQuot != null) sameQuot.OrderCount++;
                    else quotList.Add(quotDetailPer);
                });

                Response.Write(JsonHelper.toJson(quotList));
            }
        }
    }
}